package com.lgcns.andteam2.todaymenu;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.lgcns.andteam2.todaymenu.db.QueryHelper;
import com.lgcns.andteam2.todaymenu.info.PlaceInfo;
import com.lgcns.andteam2.todaymenu.item.WeekDayMenu;

/**
 * 주간 메뉴 tab을 보여주는 activity
 */
public class WeekActivity extends ListActivity {
    private static final String TAG = WeekActivity.class.getSimpleName();
    private WeekMenuAdapter mAdapter;
    private String mPlaceId;
    
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(Constants.ACTION_DB_UPDATED.equals(action)) {
                mAdapter.refreshDataSet();
            }
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.week);
        
        mAdapter = new WeekMenuAdapter(this);
        setListAdapter(mAdapter);

        ListView list = getListView();
        list.setSelector(new ColorDrawable(0x00000000)); // ListView 선택 안되게
    }
    
    @Override
    protected void onStart() {
        super.onStart();
    }
    
    @Override
    protected void onResume() {
        super.onResume();

        // 사업장 설정정보가 변경된 경우 새로 조회
        String placeId = PlaceInfo.getInstance(this).getPlaceId();
        if(mPlaceId == null || !mPlaceId.equals(placeId)) {
            mPlaceId = placeId;
            mAdapter.refreshDataSet();
        }
        
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.ACTION_DB_UPDATED);
        registerReceiver(mReceiver, filter);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
    }
    
    /**
     * 주간 메뉴 데이터&View를 가지는 adapter
     */
    private class WeekMenuAdapter extends BaseAdapter {
        private Context context;
        private ArrayList<WeekDayMenu> mMenuList;
        private LayoutInflater inflater;
        private SimpleDateFormat df = new SimpleDateFormat("M.d(E)");
        private LinearLayout.LayoutParams layoutParams;
        
        public WeekMenuAdapter(Context context) {
            super();
            this.context = context;
            mMenuList = new ArrayList<WeekDayMenu>(); // adapter 생성시에는 빈 데이터 생성
            inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            layoutParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,  // width 
                    LinearLayout.LayoutParams.WRAP_CONTENT);// height
        }
        
        /**
         * Adapter의 데이터를 query한다.
         */
        private void queryData() {
            QueryHelper.populateWeekDayMenuData(context, mMenuList);
        }
        
        @Override
        public int getCount() {
            return mMenuList.size();
        }

        @Override
        public Object getItem(int position) {
            return mMenuList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null) {
                convertView = inflater.inflate(R.layout.week_day_row, parent, false);
            } else {
                // 기존에 생성된 convertView이면, 추가되었던 gubun_row를 모두 삭제한다.
                for(int i = 0 ; i < 3 ; i++) {
                    View gubunRowView = ((LinearLayout)convertView).findViewWithTag("gubun_row" + i);
                    if(gubunRowView != null) {
                        ((LinearLayout)convertView).removeView(gubunRowView);
                    }
                }
            }
            
            WeekDayMenu menuInfo = mMenuList.get(position);
            
            TextView menuDate = (TextView)convertView.findViewById(R.id.date);
            menuDate.setText(df.format(Util.parseCalendar(menuInfo.getDate()).getTime()));
            
            // 각 gubun(아침, 점심, 저녁)에 대해 view를 생성해서 추가한다.
            for(int i = 0 ; i < 3 ; i++) {
                if(menuInfo.getMenuSize(i) > 0) { // 각 gubun에 메뉴가 존재하는 경우 gubun에 대한 영역 view 생성
                    View gubunRow = inflater.inflate(R.layout.week_gubun_row, null);
                    TextView gubun = (TextView)gubunRow.findViewById(R.id.gubun);
                    gubun.setText(menuInfo.getGubun(i));

                    // 각 gubun(끼니)에 대해 코너/메뉴의 목록을 생성하여 삽입한다.
                    LinearLayout cornerMenuLayout = (LinearLayout)gubunRow.findViewById(R.id.corner_menu_layout);
                    int menuSize = menuInfo.getMenuSize(i);
                    for(int j = 0 ; j < menuSize ; j++) {
                        View cornerMenuRow = inflater.inflate(R.layout.week_corner_menu_row, null);
                        TextView corner = (TextView)cornerMenuRow.findViewById(R.id.corner);
                        if(TextUtils.isEmpty(menuInfo.getCorner(i, j))) {
                            corner.setVisibility(View.GONE);
                        } else {
                            corner.setText(menuInfo.getCorner(i, j));
                        }
                        TextView menuName = (TextView)cornerMenuRow.findViewById(R.id.menu_name);
                        menuName.setText(menuInfo.getMenu(i, j));
                        cornerMenuLayout.addView(cornerMenuRow, layoutParams);
                    }
                    
                    gubunRow.setTag("gubun_row" + i); // convertView가 재사용 될 때 중복삽입하지 않도록 삭제해주기 위함.
                    
                    ((LinearLayout)convertView).addView(gubunRow, layoutParams);
                }
            }
            
            return convertView;
        }
        
        /**
         * Adapter의 데이터를 갱신한다.
         */
        public void refreshDataSet() {
            queryData();
            notifyDataSetChanged();
        }
    }
}
